package org.example.netty.dev1;

import com.alibaba.fastjson.JSON;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.json.JsonObjectDecoder;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import org.example.netty.dev1.codec.RpcDecoder;
import org.example.netty.dev1.codec.RpcEncoder;
import org.example.netty.dev1.entity.Request;
import org.example.netty.dev1.entity.Response;
import org.example.netty.dev1.handler.NettyClientHandler;

import java.util.UUID;

public class NettyClient {

    private final String ip;
    private final int port;



    public NettyClient(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }

    private void client(Request request){
        EventLoopGroup group = new NioEventLoopGroup();
        try{
          // 创建并初始化 Netty 客户端 Bootstrap 对象
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group);
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast(new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.cacheDisabled(null)));
                    pipeline.addLast(new ObjectEncoder());
                    pipeline.addLast(new NettyClientHandler());

                }
            });
            bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
            // 连接 RPC 服务器
            ChannelFuture future = bootstrap.connect(ip, port).sync();
            System.out.println("client connect to server is sucess");
            // 写入 RPC 请求数据并关闭连接
            future.channel().writeAndFlush(request);
            System.out.println("client send data is success");
            future.channel().closeFuture().sync();
        }catch (Exception ce){
            ce.printStackTrace();
        }finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        Request request = new Request();
        request.setRequestId(UUID.randomUUID().toString());
        request.setParameter("hello server !");
        new NettyClient("127.0.0.1", 5001).client(request);
    }


}
